﻿using System;
using System.Linq;
using Castle.DynamicProxy;
using OrchardFork.Framework.Data;
using OrchardFork.Framework.Environment;
using NPoco;

namespace OrchardFork.Framework.Aop
{
    public class InterceptorService : IInterceptor
    {
        private readonly ITransactionAttribute _transactionAttribute;
        private Boolean _isTransaction;

        //在生命周期内，获取数据事务的注入实例
        public InterceptorService(ITransactionAttribute transactionAttribute)
        {
            _transactionAttribute = transactionAttribute;
        }

        public void Intercept(IInvocation invocation)
        {

            var attributes = invocation.MethodInvocationTarget.GetCustomAttributes(false);
            //获取是否当前调用需要事务
            _isTransaction = attributes.Any(x => x.GetType() == typeof(TransactionAttribute));
            try
            {
                OnBegin(attributes);
                invocation.Proceed();
                OnComplete(attributes);
            }
            catch (Exception)
            {
                //捕获错误后的处理动作
                OnException(attributes);
            }
        }

        protected void OnBegin(object[] attributes)
        {
            _transactionAttribute.OnBegin(_isTransaction);

        }

        protected void OnComplete(object[] attributes)
        {
            _transactionAttribute.OnComplete(_isTransaction);
        }

        protected void OnException(object[] attributes)
        {
            _transactionAttribute.OnException(_isTransaction);
        }

    }
}
